//
//  AuctionManageViewController.m
//  CommunityApp
//
//  Created by 秦乾龙 on 16/12/20.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "AuctionManageViewController.h"
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
#import "AFHTTPSessionManager.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "NavView.h"
#import "ZYButton.h"
#import "Goods.h"

#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScale   ([UIScreen mainScreen].bounds.size.width)/750

@interface AuctionManageViewController ()
<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,retain)UITableView *mainTableView;
@property (nonatomic,retain)UIButton *selectClassBtn;
@property (nonatomic,retain)UIView *lineView;
@property (nonatomic,copy)NSMutableArray *dataArr;
@property (nonatomic,copy)NSMutableArray *classArr;
@property (nonatomic,copy)UIView *menuView;
@property (nonatomic,copy)ZYButton *inAction;
@property (nonatomic,copy)ZYButton *endAction;
@property (nonatomic,copy)ZYButton *flowAction;

@property (nonatomic,copy)NSString *stateStr;
@property (nonatomic,assign)NSInteger kindId;
@property (assign, nonatomic) BOOL pageToEnd;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger limit;
@end

@implementation AuctionManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.limit = 5;
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    _classArr = [def objectForKey:@"classArr"];
    _stateStr = @"1";
    _kindId = [_classArr[0][@"id"] integerValue];
    _dataArr = [NSMutableArray array];
    [self setUI];

}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        [self request];
}

- (void) setUI
{
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"拍卖管理"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(backClick)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *buttonNotice = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNotice.frame = CGRectMake(0, 0, 20, 20);
    [buttonNotice setBackgroundImage:[UIImage imageNamed:@"筛选图标"] forState:UIControlStateNormal];
    UIBarButtonItem *btnNoticeItem = [[UIBarButtonItem alloc]initWithCustomView:buttonNotice];
    [buttonNotice addTarget:self action:@selector(menuClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnNoticeItem;
    
    UIScrollView *classScrollView = [[UIScrollView alloc]init];
    classScrollView.delegate = self;
    //        hotTribeScrollView.backgroundColor = [UIColor redColor];
    classScrollView.frame = CGRectMake(0, 0, kScreenW,100*kScale);
    //    CGFloat count = 20;
    //    hotTribeScrollView.contentSize = CGSizeMake((220*kScale+10)*count, 0);
    //设置分页
    //        hotTribeScrollView.pagingEnabled = YES;
    // 是否同时运动,lock
    classScrollView.directionalLockEnabled = YES;
    //隐藏滑动条
    classScrollView.showsHorizontalScrollIndicator = FALSE;
    classScrollView.showsVerticalScrollIndicator = FALSE;
    classScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:classScrollView];
    //获取分类
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    _classArr = [def objectForKey:@"classArr"];
    //设置 content size
    float buttonWidth = 0.f;
    NSDictionary *classDic = [[NSDictionary alloc]init];
    for (NSUInteger i = 0; i<_classArr.count; i++) {
        
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        classDic = _classArr[i];
        button.tag = [classDic[@"id"]integerValue];
        [button setTitle:classDic[@"type_name"] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        CGFloat width = [classDic[@"type_name"] boundingRectWithSize:CGSizeMake(320, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        
        
        CGRect frame;
        frame.origin = CGPointMake(buttonWidth+30*kScale, 0);
        frame.size   = CGSizeMake(width+20*kScale,100*kScale);
        [button setFrame:frame];
        
        buttonWidth += CGRectGetWidth(button.frame);
        
//        button.tag = i;
        button.backgroundColor = [UIColor clearColor];
        
        [button addTarget:self
                   action:@selector(buttonEvents:)
         forControlEvents:UIControlEventTouchUpInside];
        
        //        [self configButtonWithOffsetx:0];
        if (i==0)
        {
            _selectClassBtn = button;
        }
        [classScrollView addSubview:button];
    }
    classScrollView.contentSize = CGSizeMake(buttonWidth+60*kScale, 100*kScale);
    _lineView = [[UIView alloc]init];
    _lineView.frame = CGRectMake(_selectClassBtn.frame.origin.x, 97*kScale, _selectClassBtn.frame.size.width, 3*kScale);
    _lineView.backgroundColor = [UIColor colorWithRed:14/255.0 green:161/255.0 blue:182/255.0 alpha:1.0f];
    [classScrollView addSubview:_lineView];
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 100*kScale, kScreenW, kScreenH-100*kScale-64) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self addRefreshHeader:_mainTableView];
    [self addLoadMoreFooter:_mainTableView];
    [self.view addSubview:_mainTableView];
    
    
   
}
//下拉刷新
- (void)refresh {
    [super refresh];
    [self request];
}
//上拉加载
- (void)loadMore {
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [_mainTableView.footer endRefreshing];
        return;
    }
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *urlStr = [[NSString stringWithFormat:@"%@/product/selectMyAuction?page=%ld&limit=%ld&state=%@&goods_kind=%ld",APIYIGOU,self.page,self.limit,_stateStr,_kindId]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    DYLog(@".....%ld",self.page);
    request.requestUrl =  urlStr;
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = allDic[@"data"][@"list"];
        DYLog(@"66666%@",array);
        if (array.count == 0) {
            [ViewFactory showInfoMsg:@"没有下一页了！"];
            
        }
        else if (array.count<_limit)
        {
            self.pageToEnd = YES;
        }
        self.page += 1;
        DYLog(@".....%ld",array.count);
        [_dataArr addObjectsFromArray: array];
        DYLog(@".....%ld",_dataArr.count);
        [ViewFactory dismissLoading];
        [_mainTableView reloadData];
        [_mainTableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.footer endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [_mainTableView.footer endRefreshing];
    }];
}

- (void)request
{
    self.page = 1;
    self.pageToEnd = NO;
    NSString *urlStr = [[NSString stringWithFormat:@"%@/product/selectMyAuction?page=%ld&limit=%ld&state=%@&goods_kind=%ld",APIYIGOU,self.page,self.limit,_stateStr,_kindId]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        [_dataArr removeAllObjects];
        NSLog(@"1111111%@",allDic);
        [_dataArr addObjectsFromArray: allDic[@"data"][@"list"]];
        self.page+=1;
        [_mainTableView reloadData];
        [_mainTableView.header endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    Goods *goods = [[Goods alloc]initWithDic:_dataArr[indexPath.section]];
    
    UIImageView *headerImage = [[UIImageView alloc]init];
    headerImage.frame = CGRectMake(30*kScale, 30*kScale, 150*kScale, 150*kScale);
    //        tribeHeaderImage.backgroundColor = [UIColor cyanColor];
    //    [tribeHeaderImage sd_setImageWithURL:[NSURL URLWithString:@"rest"]];
    [headerImage sd_setImageWithURL:[NSURL URLWithString:goods.headerImageUrl]];
    headerImage.layer.masksToBounds  = YES;
    headerImage.layer.cornerRadius = 8*kScale;
    [cell addSubview:headerImage];
    UILabel *introdocLable = [[UILabel alloc]init];
    introdocLable.font = [UIFont systemFontOfSize:13];
    introdocLable.numberOfLines = 3;
    //        introdocLable.lineBreakMode =  NSLineBreakByTruncatingTail;
    introdocLable.textColor = [UIColor colorWithRed:34/255.0 green:34/255.0 blue:34/255.0 alpha:1.0];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 5;
    introdocLable.text = goods.name;
    CGSize introSize = [introdocLable sizeThatFits:CGSizeMake(kScreenW-(150*kScale+3*30*kScale), MAXFLOAT)];
    
    //        NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:style};
    //        introdocLable.attributedText = [[NSAttributedString alloc]initWithString:introdocLable.text attributes:attributes];
    
    
    introdocLable.frame = CGRectMake(150*kScale+2*30*kScale, headerImage.frame.origin.y, kScreenW-(150*kScale+3*30*kScale), introSize.height);
    
    [cell addSubview:introdocLable];
    UILabel *priceLable= [[UILabel alloc]init];
    priceLable.font = [UIFont systemFontOfSize:13];
    if([goods.price isEqualToString:@"<null>"] || goods.price.length == 0 || goods.price == nil){
        priceLable.text = [NSString stringWithFormat:@"当前价：¥%@",goods.startPrice];
    }
    else
    {
        priceLable.text = [NSString stringWithFormat:@"当前价：¥%@",goods.price];
    }
    
    CGSize numSize = CGSizeZero;
    
    numSize = [priceLable sizeThatFits:CGSizeMake(MAXFLOAT, 40*kScale)];
    priceLable.frame = CGRectMake(150*kScale+2*30*kScale, headerImage.frame.origin.y+150*kScale-40*kScale, numSize.width, 40*kScale);
    
    
    priceLable.textColor = [UIColor colorWithRed:189/255.0 green:40/255.0 blue:40/255.0 alpha:1.0];
    [cell addSubview:priceLable];
    UILabel *sellerCountLable= [[UILabel alloc]init];
    sellerCountLable.font = [UIFont systemFontOfSize:11];
    if([goods.startPrice isEqualToString:@"<null>"] || goods.startPrice.length == 0 || goods.startPrice == nil){
    sellerCountLable.text = [NSString stringWithFormat:@"起拍价:"];
    }
    else
    {
        sellerCountLable.text = [NSString stringWithFormat:@"起拍价:%@",goods.startPrice];
    }
    sellerCountLable.textColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1.0];
    CGSize seallerSize = [sellerCountLable sizeThatFits:CGSizeMake(MAXFLOAT, 40*kScale)];
    sellerCountLable.frame = CGRectMake(150*kScale+3*30*kScale+numSize.width, headerImage.frame.origin.y+150*kScale-40*kScale,seallerSize.width, 40*kScale);
    [cell addSubview:sellerCountLable];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 210*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0)
    {
        return 30*kScale;
    }
    return 20*kScale;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)buttonEvents:(ZYButton*)sender
{
    _selectClassBtn = sender;
    _kindId = sender.tag;
    _lineView.frame = CGRectMake(_selectClassBtn.frame.origin.x, 97*kScale, _selectClassBtn.frame.size.width, 3*kScale);
    [self request];
}

//菜单
- (void)menuClick:(UIButton*)sender
{
    CGFloat btnH = 74*kScale;
    //    CGFloat btnW = 150*kScale;
    
    if (!_menuView) {
        _menuView = [[UIView alloc] init];
        _menuView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_menuView];
        _inAction = [ZYButton buttonWithType:UIButtonTypeCustom];
        //        _inAction.frame = CGRectMake(0, 2*kScale, btnW, btnH);
        _inAction.backgroundColor = [UIColor blackColor];
        [_inAction addTarget:self action:@selector(stateClick:) forControlEvents:UIControlEventTouchUpInside];
        _inAction.tag = 1;
        [_menuView addSubview:_inAction];
        UIImageView *inSellImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"拍卖中图标"]];
        //        inSellImage.backgroundColor = [UIColor whiteColor];
        CGFloat sellImageH = 40*kScale;
        inSellImage.frame = CGRectMake(20*kScale, (btnH-sellImageH)/2, sellImageH, sellImageH);
        [_inAction addSubview:inSellImage];
        
        //        CGFloat titleW = 80*kScale;
        UILabel *inSelltitle = [[UILabel alloc]init];
        inSelltitle.text = @"拍卖中";
        inSelltitle.font = [UIFont systemFontOfSize:13];
        CGSize titleSize = [inSelltitle sizeThatFits:CGSizeMake(MAXFLOAT, btnH)];
        inSelltitle.textColor = [UIColor whiteColor];
        inSelltitle.frame = CGRectMake(40*kScale+sellImageH, 0, titleSize.width, btnH);
        [_inAction addSubview:inSelltitle];
        _inAction.frame = CGRectMake(0, 2*kScale, sellImageH+20*kScale*3+titleSize.width, btnH);
        _endAction = [ZYButton buttonWithType:UIButtonTypeCustom];
        //        _endAction.frame = CGRectMake(0, 2*kScale*2+btnH, btnW, btnH);
        [_endAction addTarget:self action:@selector(stateClick:) forControlEvents:UIControlEventTouchUpInside];
        _endAction.tag = 0;
        _endAction.backgroundColor = [UIColor blackColor];
        [_menuView addSubview:_endAction];
        UIImageView *downGoodsImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"已结束图标"]];
        //        downGoodsImage.backgroundColor = [UIColor whiteColor];
        CGFloat downGoodsImageH = 40*kScale;
        downGoodsImage.frame = CGRectMake(20*kScale, (btnH-sellImageH)/2, downGoodsImageH, downGoodsImageH);
        [_endAction addSubview:downGoodsImage];
        
        UILabel *downGoodsTitle = [[UILabel alloc]init];
        downGoodsTitle.text = @"已结束";
        downGoodsTitle.font = [UIFont systemFontOfSize:13];
        downGoodsTitle.textColor = [UIColor whiteColor];
        downGoodsTitle.frame = CGRectMake(40*kScale+sellImageH, 0, titleSize.width, btnH);
        [_endAction addSubview:downGoodsTitle];
        _endAction.frame = CGRectMake(0, 2*kScale*2+btnH, sellImageH+20*kScale*3+titleSize.width, btnH);
    }
    if (sender.selected==YES) {
        _menuView.frame = CGRectMake(kScreenW*5, 0, 0, 0);
        
    }
    else
    {
        _menuView.frame = CGRectMake(kScreenW-180*kScale, 0, 150*kScale, 152*kScale);
    }
    sender.selected = !sender.selected;
    //    NSLog(@".....%d",sender.selected);
}
- (void)stateClick:(ZYButton*)sender
{
    _menuView.frame = CGRectMake(kScreenW*2, 0, 0, 0);
    _stateStr = [NSString stringWithFormat:@"%ld",(long)sender.tag];
    NSLog(@"===%@",_stateStr);
    [self request];
}
//返回
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
